import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, message, Spin } from 'antd';
import {
  WeaLocaleProvider,
  WeaMoreButton,
  WeaDialog,
  WeaSearchGroup,
  WeaTableEditable,
  WeaNewScroll,
} from 'ecCom';
import { RenderForm } from '../util';

const getLabel = WeaLocaleProvider.getLabel;
const showName = 'ruleEdit';

@inject('settingStore')
@observer
class Edit extends Component {
  constructor(props) {
    super(props);
    this.prefixCls = `${props.class}-edit`;
  }

  onCancel = () => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    const { setStoreState, editForm } = ruleStore;
    setStoreState({ editVisible: false, editFields: [] });
    editForm.resetForm();
    editForm.setCondition([]);
  };

  getForm = (form, fields) => {
    // const preCls = 'email-form'
    const { isFormInit } = form;
    let group = [];
    isFormInit &&
      toJS(fields) &&
      toJS(fields).map((c) => {
        let items = [];
        c.items.map((field) => {
          if (field.domkey[0] === 'accountType') {
            form.getFormParams().mailType * 1 === 0 &&
              items.push({ com: RenderForm(form, field) });
          } else {
            items.push({ com: RenderForm(form, field) });
          }
        });
        group.push(
          <WeaSearchGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaSearchGroup@6t9nh0@${showName}SearchGroup`}
            col={1}
            title={c.title}
            needTigger={true}
            showGroup={c.defaultshow}
            items={items}
          />,
        );
      });
    return group;
  };

  onSubmit = () => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    const {
      operateUserEmailRule,
      editForm,
      getEmailRuleList,
      isEdit,
      editRule,
      editAction,
      ruleId,
      editMailType,
    } = ruleStore;
    const formParams = editForm.getFormParams() || {};
    let params = { ...formParams, operation: 'baseSave' };
    let flag = true;
    if (editMailType == '0') {
      // 外部邮件
      for (let initem of toJS(editRule)) {
        // 验证执行条件必填项
        if (
          initem.test1[0] === '1' &&
          (initem.test1[2] === '' || initem.test1[2] === undefined)
        ) {
          flag = false;
          message.warning(getLabel(519518, '主题不能为空，请重新选择！'));
          break;
        } else if (
          initem.test1[0] === '2' &&
          (initem.test1[2] === '' || initem.test1[2] === undefined)
        ) {
          flag = false;
          message.warning(getLabel(519519, '发件人不能为空，请重新选择！'));
          break;
        } else if (
          initem.test1[0] === '3' &&
          (initem.test1[2] === '' || initem.test1[2] === undefined)
        ) {
          flag = false;
          message.warning(getLabel(519520, '收件人不能为空，请重新选择！'));
          break;
        } else if (
          initem.test1[0] === '4' &&
          (initem.test1[2] === '' || initem.test1[2] === undefined)
        ) {
          flag = false;
          message.warning(getLabel(519521, '抄送人不能为空，请重新选择！'));
          break;
        } else if (
          initem.test1[0] === '6' &&
          (initem.test1[2] === '' || initem.test1[2] === undefined)
        ) {
          flag = false;
          message.warning(getLabel(519522, '发件日期不能为空，请重新选择！'));
          break;
        } else if (
          initem.test1[0] === '7' &&
          (initem.test1[2] === '' || initem.test1[2] === undefined)
        ) {
          flag = false;
          message.warning(getLabel(519523, '邮件大小不能为空，请重新选择！'));
          break;
        }
      }
    } else if (editMailType == '1') {
      // 内部邮件
      for (let item of toJS(editRule)) {
        // 验证执行条件必填项
        if (
          item.test1[0] === '1' &&
          (item.test1[2] === '' || item.test1[2] === undefined)
        ) {
          flag = false;
          message.warning(getLabel(519518, '主题不能为空，请重新选择！'));
          break;
        } else if (
          item.test1[0] === '2' &&
          (item.test1[2] === undefined ||
            item.test1[2].value === '' ||
            item.test1[2].value === '0')
        ) {
          flag = false;
          message.warning(getLabel(519519, '发件人不能为空，请重新选择！'));
          break;
        } else if (
          item.test1[0] === '3' &&
          (item.test1[2] === undefined ||
            item.test1[2].value === '' ||
            item.test1[2].value === '0')
        ) {
          flag = false;
          message.warning(getLabel(519520, '收件人不能为空，请重新选择！'));
          break;
        } else if (
          item.test1[0] === '4' &&
          (item.test1[2] === undefined ||
            item.test1[2].value === '' ||
            item.test1[2].value === '0')
        ) {
          flag = false;
          message.warning(getLabel(519521, '抄送人不能为空，请重新选择！'));
          break;
        } else if (
          item.test1[0] === '6' &&
          (item.test1[2] === '' || item.test1[2] === undefined)
        ) {
          flag = false;
          message.warning(getLabel(519522, '发件日期不能为空，请重新选择！'));
          break;
        } else if (
          item.test1[0] === '7' &&
          (item.test1[2] === '' || item.test1[2] === undefined)
        ) {
          flag = false;
          message.warning(getLabel(519523, '邮件大小不能为空，请重新选择！'));
          break;
        }
      }
    }

    if (flag) {
      // 验证执行动作必填项
      toJS(editAction) &&
        toJS(editAction).map((item) => {
          if (item.test2[0] === '6' && item.test2[1] === '') {
            flag = false;
            message.warning(getLabel('506451', '标签不能为空，请重新选择！'));
          } else if (
            item.test2[0] === '4' &&
            (item.test2[1] === '' ||
              item.test2[1] === undefined ||
              item.test2[1].value === '' ||
              item.test2[1].value === '0')
          ) {
            flag = false;
            message.warning(
              getLabel('506452', '导出客户联系不能为空，请重新选择！'),
            );
          }
        });
    }

    if (flag) {
      isEdit &&
        (params = {
          ...params,
          operation: 'updateSave',
          mailConditionArray: JSON.stringify(toJS(editRule)),
          mailActionArray: JSON.stringify(toJS(editAction)),
          ruleId,
        });
      operateUserEmailRule(params).then((res) => {
        if (res.flag) {
          getEmailRuleList('', true);
          this.onCancel();
        } else {
          let errorMsg =
            res.message === 'repeat'
              ? getLabel('26603', '名称重复')
              : getLabel(21809, '保存失败，请重试！');
          message.error(errorMsg);
        }
      });
    }
  };

  onDetailSubmit = () => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    const {
      operateUserEmailRule,
      editForm,
      getEmailRuleList,
      updateRule,
      setStoreState,
    } = ruleStore;
    const formParams = editForm.getFormParams() || {};
    let params = {
      ...formParams,
      operation: 'baseSave',
      isdetail: '1',
      type: 'update',
    };
    operateUserEmailRule(params).then((res) => {
      const id = res.emailRuleEntity && res.emailRuleEntity.id;
      setStoreState({ ruleId: id });
      if (res.flag) {
        updateRule({ id, type: 'update' });
        getEmailRuleList('', true);
      } else {
        let errorMsg =
          res.message === 'repeat'
            ? getLabel('26603', '名称重复')
            : getLabel(21809, '保存失败，请重试！');
        message.error(errorMsg);
      }
    });
  };

  renderTable = (editRule, type, editAction) => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    const {
      ruleconditioninfo_in,
      ruleconditioninfo_out,
      actionconditioninfo,
    } = ruleStore;
    const columns = [
      {
        title: getLabel(387685, '自定义条件设置'), // 列名
        dataIndex: 'test1', // 列的id 对应数据
        key: 'test1', // 前端渲染key值
        com: [
          {
            label: '',
            type: 'CASCADER',
            key: 'test1',
            compDef: type
              ? toJS(ruleconditioninfo_in)
              : toJS(ruleconditioninfo_out),
          },
        ],
        colSpan: 1,
      },
    ];
    const columnsAction = [
      {
        title: getLabel(387685, '自定义条件设置'), // 列名
        dataIndex: 'test2', // 列的id 对应数据
        key: 'test2', // 前端渲染key值
        com: [
          {
            label: '',
            type: 'CASCADER',
            key: 'test2',
            compDef: toJS(actionconditioninfo),
          },
        ],
        colSpan: 1,
      },
    ];
    return (
      <div className={`${this.prefixCls}-editRule`}>
        <WeaTableEditable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTableEditable@q9mpb6`}
          title={getLabel(19841, '执行条件')}
          className="edit-rule"
          datas={toJS(editRule)}
          columns={columns}
          onChange={this.onRuleChange}
        />
        <WeaTableEditable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTableEditable@lwcp69`}
          title={getLabel(19831, '执行动作')}
          className="edit-action"
          datas={toJS(editAction)}
          columns={columnsAction}
          onChange={this.onActionChange}
        />
      </div>
    );
  };

  onRuleChange = (v) => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    ruleStore.setStoreState({ editRule: v });
  };
  onActionChange = (v) => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    ruleStore.setStoreState({ editAction: v });
  };

  onSave = () => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    ruleStore.editSubmit(this.onSubmit);
  };

  onSaveToDetail = () => {
    const {
      settingStore: { ruleStore },
    } = this.props;
    ruleStore.editSubmit(this.onDetailSubmit);
  };

  render() {
    const {
      settingStore: { ruleStore },
    } = this.props;
    const {
      editVisible,
      editTitle,
      editForm,
      editFields,
      isEdit,
      editLoading,
      editRule,
      editMailType,
      editAction,
    } = ruleStore;
    const buttons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@5ub8z7@${showName}save`}
        type="primary"
        onClick={this.onSave}
      >
        {getLabel(30986, '保存')}
      </Button>,
      !isEdit && (
        <Button
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Button@zfo0jh@${showName}savetodetail`}
          type="primary"
          onClick={this.onSaveToDetail}
        >
          {getLabel(32159, '保存并进入详细设置')}
        </Button>
      ),
      <WeaMoreButton
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaMoreButton@5ce7rj@${showName}more`}
      />,
    ];
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@3r9sbc`}
        icon="icon-coms-email"
        iconBgcolor="#a0b0ba"
        title={editTitle}
        style={{ width: 800, maxHeight: 500 }}
        className={this.prefixCls}
        visible={editVisible}
        onCancel={this.onCancel}
        buttons={buttons}
        loading={true}
        hasScroll
      >
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@ipupob`}
          spinning={editLoading}
        >
          <WeaNewScroll
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaNewScroll@ym4bdm`}
            style={{ maxHeight: 500 }}
          >
            {this.getForm(editForm, editFields, isEdit)}
            {isEdit && this.renderTable(editRule, editMailType, editAction)}
          </WeaNewScroll>
        </Spin>
      </WeaDialog>
    );
  }
}

export default Edit;
